package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.StrategyThemeQuery;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
public class StrategyThemeServiceImpl implements IStrategyThemeService {
    @Autowired
    private StrategyThemeRepository strategyThemeRepository;

    @Autowired
    private MongoTemplate mongoTemplate;//可以操作数据库

    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);
        strategyThemeRepository.save(strategyTheme);
    }


    @Override
    public void updateInfo(StrategyTheme strategyTheme) {

    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        strategyThemeRepository.save(strategyTheme);
    }

    @Override
    public StrategyTheme get(String id) {
        Optional byId = strategyThemeRepository.findById(id);
//强转
        return (StrategyTheme) byId.orElse(null);//如果是空是就返回空值,否则返回对象
    }

    @Override
    public List<StrategyTheme> listAll() {
        List<StrategyTheme> strategyThemes = strategyThemeRepository.findAll();
        return strategyThemes;
    }

    @Override
    public void delete(String id) {
        strategyThemeRepository.deleteById(id);
    }


    /**
     * 抽取的新增/修改方法
     * @param strategyTheme
     */
    @Override
    public void saveOrUpdate(StrategyTheme strategyTheme) {
        if (!StringUtils.hasLength(strategyTheme.getId())) {
            this.save(strategyTheme);
        } else {
//            //修改操作
            this.update(strategyTheme);
        }
    }

    @Override
    public Page<StrategyTheme> query(StrategyThemeQuery qo) {
        //查询对象
        Query query = new Query();
        //查询出总数条数
        long rows = mongoTemplate.count(query, StrategyTheme.class);
        if (rows == 0) {
            return  Page.empty();//如果总数条数是0,就返回空集合
        }
        //分页对象(设置当前页从0开始算,还有页面显示条数,按sequence这个列正序排列 )  
        //  Sort.Direction.ASC,表示按正序排列表格
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1,
                qo.getPageSize(), Sort.Direction.ASC, "sequence");
        //给查询对象
        query.with(pageable);
        List<StrategyTheme> list = mongoTemplate.find(query, StrategyTheme.class);

        return  new PageImpl<StrategyTheme>(list,pageable,rows);//相当于pageResult对象

    }

}
